class Solution: def twoSum(self, nums, target): idxDict = dict() idx_list = [] for idx, num in enumerate(nums): if target - num in idxDict: idx_list.append([idxDict[target - num], idx]) idxDict[num] = idx return idx_list def threeSum(self, num): num.sort() res = dict() result = [] for i in range(len(num)-2): # 遍历至倒数第三个,后面两个指针 if (i == 0 or num[i] > num[i-1]) and num[i] <= 0: # 只检索不重复并且目标数(第一个数)小于等于0的情况 left = i + 1; # right = len(num) - 1 result_idx = self.twoSum(num[left:], -num[i]) for each_idx in result_idx: # 数组后方切片后给twoSum each_result = [num[i], num[each_idx[0]+(i+1)], num[each_idx[1]+(i+1)]] if str(each_result) not in res: res[str(each_result)] = each_result for value in res.values(): result.append(value) return result
class Solution: def threeSum(self, num): num.sort() res = [] for i in range(len(num)-2): # 遍历至倒数第三个,后面两个指针 if i == 0 or num[i] > num[i-1]: left = i + 1 right = len(num) - 1 while left < right: # 值得注意的是,这里左右指针将这个数所有情况都遍历加入,所以遇到同样的数直接跳过 if num[left] + num[right] == -num[i]: res.append([num[i], num[left], num[right]]) left += 1; right -= 1 while left < right and num[left] == num[left-1]: left +=1 while left < right and num[right] == num[right+1]: right -= 1 elif num[left] + num[right] < -num[i]: while left < right: left += 1 if num[left] > num[left-1]: break else: while left < right: right -= 1 if num[right] < num[right+1]: break return res
class Solution { public List<List<Integer>> threeSum(int[] nums) { Arrays.sort(nums); List<List<Integer>> list = new ArrayList<>(); int i = 0; while (i < nums.length - 2) { if (nums[i] > 0) break; int left = i + 1, right = nums.length - 1; while (left < right) { int sum = nums[i] + nums[left] + nums[right]; if (sum == 0) { list.add(Arrays.asList(nums[i], nums[left++], nums[right--])); while (left < right && nums[left] == nums[left - 1]) ++left; while (left < right && nums[right] == nums[right + 1]) --right; } else if (sum < 0) ++left; else --right; // ++写在前面,说明++先有效,即b要+1,然后赋值给a } while (nums[i] == nums[++i] && i < nums.length - 2) ; // 如果数字重复跳过遍历 } return list; } }
总结
in 操作符在 dict 里面可以理解为是 O(1) 的时间复杂度,在 list 里面可以理解为是 O(n)。